<template>
  <div class="report-container">
    <!-- 标题和操作区 -->
    <div class="header">
      <div class="title">
        <el-page-header @back="goBack" title="返回" :content="'扫描报告'" />
      </div>
      <div class="actions">
        <el-button type="primary" @click="exportReport">导出报告</el-button>
        <el-button 
          v-if="selectedFilesMap.size > 0"
          @click="clearAllSelection"
        >
          清除选择 ({{ selectedFilesMap.size }})
        </el-button>
        <el-button 
          type="danger" 
          @click="() => { console.log('清理按钮被点击'); handleCleanup(); }" 
          :disabled="selectedFilesMap.size === 0"
        >
          清理选中文件 ({{ selectedFilesMap.size }})
        </el-button>
      </div>
    </div>

    <!-- 扫描状态和统计 -->
    <div class="status-bar" v-if="scanning">
      <el-progress :percentage="scanProgress" />
      <span class="status-text">正在扫描文件...</span>
    </div>

    <!-- 调试信息 -->
    <!-- <div v-if="selectedFiles.length > 0" style="margin-bottom: 10px; padding: 10px; background: #e6f7ff; border-radius: 4px;">
      <p><strong>已选中文件调试信息:</strong></p>
      <p>选中文件数量: {{ selectedFiles.length }}</p>
      <p>选中文件ID: {{ selectedFiles.map(f => f.id).join(', ') }}</p>
      <p>选中文件详情: {{ JSON.stringify(selectedFiles, null, 2) }}</p>
    </div> -->

    <!-- 文件列表 -->
    <div class="file-list">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="files"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="文件名" prop="file_name" min-width="200">
          <template #default="{ row }">
            <el-tooltip
              :content="row.file_path"
              placement="top"
              :show-after="1000"
            >
              <span>{{ row.file_name }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="文件路径" prop="file_path" min-width="300" />
        <el-table-column label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 'not_seeding' ? 'danger' : 'success'">
              {{ row.status === 'not_seeding' ? '未做种' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="danger"
              link
              @click="handleDeleteSingle(row)"
              :disabled="row.status === 'deleted'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="totalFiles"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useClientStore } from '../stores/client'

const route = useRoute()
const router = useRouter()
const clientStore = useClientStore()

const loading = ref(false)
const scanning = ref(false)
const scanProgress = ref(0)
const files = ref([])
const selectedFiles = ref([])
const selectedFilesMap = ref(new Map()) // 用于跨页保存选中状态
const currentPage = ref(1)
const pageSize = ref(20)
const totalFiles = ref(0)
const tableRef = ref()
const lastSelectionIndex = ref(-1)
const isShiftPressed = ref(false)
const isDragging = ref(false)
const dragStartIndex = ref(-1)
const dragEndIndex = ref(-1)

// 初始化
onMounted(async () => {
  try {
    // 检查是否有正在进行的扫描
    await checkScanStatus();
    // 加载扫描结果
    await loadFiles();
    
    // 添加键盘事件监听
    document.addEventListener('keydown', handleKeyDown)
    document.addEventListener('keyup', handleKeyUp)
    
    // 添加鼠标事件监听
    document.addEventListener('mousedown', handleMouseDown)
    document.addEventListener('mousemove', handleMouseMove)
    document.addEventListener('mouseup', handleMouseUp)
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('初始化失败');
  }
});

// 清理事件监听
onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeyDown)
  document.removeEventListener('keyup', handleKeyUp)
  document.removeEventListener('mousedown', handleMouseDown)
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
})

// 检查扫描状态
const checkScanStatus = async () => {
  try {
    const status = await clientStore.getScanStatus();
    scanning.value = status.status === 'scanning';
    if (scanning.value) {
      scanProgress.value = status.progress || 0;
      // 如果正在扫描，每2秒检查一次状态
      setTimeout(checkScanStatus, 2000);
    }
  } catch (error) {
    console.error('获取扫描状态失败:', error);
    ElMessage.error('获取扫描状态失败');
  }
};

// 加载文件列表
const loadFiles = async () => {
  loading.value = true;
  try {
    // 计算分页参数
    const skip = (currentPage.value - 1) * pageSize.value;
    const limit = pageSize.value;
    
    // 获取总数
    const countResponse = await clientStore.getScanResultsCount('not_seeding');
    totalFiles.value = countResponse || 0;
    
    // 获取当前页数据
    const response = await clientStore.getScanResults('not_seeding', skip, limit);
    files.value = response || [];
    
    // 恢复之前选中的文件
    restoreSelection();
    
    // 如果没有扫描结果，显示提示信息
    if (totalFiles.value === 0) {
      ElMessage.info('没有找到未做种的文件');
    } else {
      ElMessage.success(`找到 ${totalFiles.value} 个未做种的文件`);
    }
  } catch (error) {
    console.error('加载文件列表失败:', error);
    ElMessage.error('加载文件列表失败');
  } finally {
    loading.value = false;
  }
};

// 恢复选中状态
const restoreSelection = () => {
  nextTick(() => {
    files.value.forEach(file => {
      // 使用字符串比较，确保ID类型一致
      const fileId = String(file.id);
      if (selectedFilesMap.value.has(fileId)) {
        tableRef.value.toggleRowSelection(file, true);
      }
    });
  });
};



// 格式化文件大小
const formatFileSize = (size: number) => {
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(2)} ${units[index]}`
}

// 处理文件选择
const handleSelectionChange = (selection) => {
  console.log('表格选择变化:', selection);
  
  // 更新选中状态到Map
  // 先移除当前页的所有文件
  files.value.forEach(file => {
    const fileId = String(file.id);
    selectedFilesMap.value.delete(fileId);
  });
  
  // 添加新选中的文件
  selection.forEach(file => {
    const fileId = String(file.id);
    selectedFilesMap.value.set(fileId, file);
  });
  
  // 更新selectedFiles为所有选中的文件
  selectedFiles.value = Array.from(selectedFilesMap.value.values());
}

// 处理单个选择 - 只在非Shift状态下处理
const handleSelect = (selection, row) => {
  const currentIndex = files.value.findIndex(file => file.id === row.id)
  
  if (!isShiftPressed.value || lastSelectionIndex.value === -1 || currentIndex === -1) {
    // 普通选择，更新最后选择索引
    lastSelectionIndex.value = currentIndex
  }
}

// 处理行点击和复选框点击 - 统一处理Shift选择
const handleRowClick = (row, column, event) => {
  if (column.type === 'selection') return // 复选框点击由handleSelect处理
  
  const index = files.value.findIndex(file => file.id === row.id)
  if (index === -1) return
  
  if (isShiftPressed.value && lastSelectionIndex.value !== -1) {
    // Shift+点击选择范围
    const start = Math.min(lastSelectionIndex.value, index)
    const end = Math.max(lastSelectionIndex.value, index)
    
    // 获取当前选择状态（基于第一个点击的文件）
    const firstFile = files.value[lastSelectionIndex.value]
    const firstFileId = String(firstFile.id)
    const isSelected = !selectedFilesMap.value.has(firstFileId)
    
    // 批量选择范围内的所有文件
    const filesToSelect = []
    for (let i = start; i <= end; i++) {
      const file = files.value[i]
      if (file) {
        filesToSelect.push(file)
      }
    }
    
    // 统一设置选择状态 - 让handleSelectionChange处理Map更新
      filesToSelect.forEach(file => {
        tableRef.value.toggleRowSelection(file, isSelected)
      })
    
    lastSelectionIndex.value = index
  } else {
    // 普通点击切换选择状态
    tableRef.value.toggleRowSelection(row)
    lastSelectionIndex.value = index
  }
}

// 处理全选
const handleSelectAll = (selection) => {
  lastSelectionIndex.value = -1
}

// 键盘事件处理
const handleKeyDown = (event) => {
  if (event.key === 'Shift') {
    isShiftPressed.value = true
  }
}

const handleKeyUp = (event) => {
  if (event.key === 'Shift') {
    isShiftPressed.value = false
  }
}

// 鼠标拖拽选择
const handleMouseDown = (event) => {
  // 检查是否在表格区域内
  const tableElement = tableRef.value?.$el
  if (!tableElement || !tableElement.contains(event.target)) return
  
  // 排除操作列和复选框的点击
  const target = event.target
  const isActionColumn = target.closest('.el-table__column--fixed-right')
  const isCheckbox = target.type === 'checkbox' || target.closest('.el-checkbox') || target.closest('.el-table__column--selection')
  if (isActionColumn || isCheckbox) return
  
  const row = target.closest('.el-table__row')
  if (row) {
    const rowIndex = Array.from(row.parentNode.children).indexOf(row)
    if (rowIndex !== -1) {
      isDragging.value = true
      dragStartIndex.value = rowIndex
      dragEndIndex.value = rowIndex
      
      // 添加拖拽样式
      document.body.classList.add('dragging')
      
      // 防止文本选择
      event.preventDefault()
    }
  }
}

const handleMouseMove = (event) => {
  if (!isDragging.value) return
  
  const tableElement = tableRef.value?.$el
  if (!tableElement) return
  
  const rows = tableElement.querySelectorAll('.el-table__row')
  const mouseY = event.clientY
  
  let newEndIndex = -1
  
  for (let i = 0; i < rows.length; i++) {
    const row = rows[i]
    const rect = row.getBoundingClientRect()
    
    if (mouseY >= rect.top && mouseY <= rect.bottom) {
      newEndIndex = i
      break
    }
  }
  
  if (newEndIndex !== -1 && newEndIndex !== dragEndIndex.value) {
    dragEndIndex.value = newEndIndex
    updateDragSelection()
  }
}

const handleMouseUp = () => {
  if (isDragging.value) {
    // 执行最终选择
    if (dragStartIndex.value !== -1 && dragEndIndex.value !== -1) {
      const start = Math.min(dragStartIndex.value, dragEndIndex.value)
      const end = Math.max(dragStartIndex.value, dragEndIndex.value)
      
      // 选择拖拽范围内的文件 - 让handleSelectionChange处理Map更新
      for (let i = start; i <= end; i++) {
        const file = files.value[i]
        if (file) {
          tableRef.value.toggleRowSelection(file, true)
        }
      }
    }
    
    isDragging.value = false
    dragStartIndex.value = -1
    dragEndIndex.value = -1
    
    // 移除拖拽样式
    document.body.classList.remove('dragging')
    
    // 移除高亮样式
    const rows = tableRef.value?.$el?.querySelectorAll('.el-table__row')
    if (rows) {
      rows.forEach(row => row.classList.remove('drag-selecting'))
    }
  }
}

const updateDragSelection = () => {
  if (dragStartIndex.value === -1 || dragEndIndex.value === -1) return
  
  const start = Math.min(dragStartIndex.value, dragEndIndex.value)
  const end = Math.max(dragStartIndex.value, dragEndIndex.value)
  
  // 更新视觉高亮
  const rows = tableRef.value?.$el?.querySelectorAll('.el-table__row')
  if (rows) {
    rows.forEach((row, index) => {
      if (index >= start && index <= end) {
        row.classList.add('drag-selecting')
      } else {
        row.classList.remove('drag-selecting')
      }
    })
  }
  
  // 更新最后选择索引
  lastSelectionIndex.value = dragEndIndex.value
}

// 处理分页
const handleSizeChange = async (size: number) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  await loadFiles();
};

const handleCurrentChange = async (page: number) => {
  currentPage.value = page;
  await loadFiles();
};

// 导出报告
const exportReport = async () => {
  try {
    // 获取所有扫描结果，不限制数量
    const totalCount = await clientStore.getScanResultsCount('not_seeding')
    const allFiles = await clientStore.getScanResults('not_seeding', 0, totalCount)
    
    const data = allFiles.map(file => ({
      文件名: file.file_name,
      路径: file.file_path,
      大小: formatFileSize(file.file_size),
      状态: file.status === 'not_seeding' ? '未做种' : '已删除'
    }))

    const csv = convertToCSV(data)
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', `scan-report-${Date.now()}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success(`成功导出 ${allFiles.length} 个文件的扫描报告`)
  } catch (error) {
    console.error('导出报告失败:', error)
    ElMessage.error('导出报告失败，请重试')
  }
}

// 转换为CSV
const convertToCSV = (data) => {
  if (data.length === 0) return ''
  const headers = Object.keys(data[0])
  const rows = [
    headers.join(','),
    ...data.map(obj => headers.map(key => `"${obj[key]}"`).join(','))
  ]
  return rows.join('\n')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 处理单个文件删除
const handleDeleteSingle = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确认删除文件：${file.file_name}？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await clientStore.deleteFiles([file.id])
    ElMessage.success('删除成功')
    
    // 从选中状态中移除该文件
    selectedFilesMap.value.delete(file.id)
    
    await loadFiles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 清除所有选择
const clearAllSelection = () => {
  selectedFilesMap.value.clear()
  selectedFiles.value = []
  
  // 清除当前页的选中状态
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
  
  ElMessage.success('已清除所有选择')
}

// 处理批量清理
const handleCleanup = async () => {
  console.log('=== 开始处理清理操作 ===');
  console.log('handleCleanup 被调用');
  console.log('selectedFilesMap.size:', selectedFilesMap.value.size);
  
  // 确保有选中的文件
  if (selectedFilesMap.value.size === 0) {
    console.log('没有选中的文件，显示警告');
    ElMessage.warning('请先选择要清理的文件');
    return;
  }
  
  console.log('开始处理文件ID...');
  
  // 获取所有选中的文件ID - 直接使用文件ID，不进行数值转换
  const allSelectedFiles = Array.from(selectedFilesMap.value.values());
  console.log('所有选中的文件:', allSelectedFiles);
  
  const validFiles = allSelectedFiles.filter(file => {
    console.log('检查文件:', file);
    return file && file.id !== undefined && file.id !== null && String(file.id).trim() !== '';
  });
  
  console.log('有效文件列表:', validFiles);
  
  const fileIds = validFiles
    .map(file => String(file.id).trim())
    .filter(id => id && id !== '0') // 过滤空值和0
    .join(',');
  
  console.log('最终文件ID字符串:', fileIds);
  
  // 如果没有有效的文件 ID，显示警告并返回
  if (!fileIds) {
    console.log('没有有效的文件ID，显示警告');
    ElMessage.warning('选中的文件没有有效的 ID');
    return;
  }
  
  console.log('当前路由参数:', route.params);
  console.log('route.params.id:', route.params.id);
  
  // 检查当前路由是否有 id 参数
  try {
    let targetRoute;
    if (route.params.id) {
      // 如果有 id 参数，使用 cleanupByClient 路由
      const clientId = String(route.params.id);
      console.log('客户端ID:', clientId, '类型:', typeof clientId);
      
      targetRoute = {
        name: 'cleanupByClient',
        params: { id: clientId },
        query: { files: fileIds }
      };
      console.log('使用 cleanupByClient 路由:', targetRoute);
    } else {
      // 如果没有 id 参数，使用 cleanup 路由
      targetRoute = {
        name: 'cleanup',
        query: { files: fileIds }
      };
      console.log('使用 cleanup 路由:', targetRoute);
    }
    
    console.log('开始路由导航...');
    console.log('目标路由对象:', JSON.stringify(targetRoute));
    
    await router.push(targetRoute);
    console.log('路由导航成功');
    
  } catch (error) {
    console.error('路由导航错误:', error);
    console.error('错误详情:', {
      name: error.name,
      message: error.message,
      stack: error.stack
    });
    ElMessage.error('导航到清理页面失败: ' + (error.message || '未知错误'));
  }
  
  console.log('=== 清理操作处理完成 ===');
};
</script>

<style scoped>
.report-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.status-bar {
  margin-bottom: 20px;
}

.status-text {
  margin-left: 10px;
  color: #666;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.actions {
  display: flex;
  gap: 10px;
}

/* 拖拽选择样式 */
:deep(.el-table__row) {
  user-select: none;
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  cursor: pointer;
}

:deep(.el-table__row.drag-selecting) {
  background-color: #e6f7ff !important;
}

:deep(.el-table__row.drag-selecting:hover) {
  background-color: #bae7ff !important;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #409eff;
}

/* 防止拖拽时选中文本 */
body.dragging {
  user-select: none;
}

body.dragging :deep(.el-table__row) {
  cursor: grabbing;
}
</style>
